﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Mindfor.Web.Data;
using NHibernate;
using NHibernate.Linq;
using Mindfor.Web.Models;
using System.Web.Mvc;

namespace Mindfor.Web.Modules.News
{
	public class NewsModule : ModuleBase
	{
		//custom role for News Module. News Manager can add, edit and delete newsItems
		public const string NewsRole = "NewsManager";

		public override string FriendlyName
		{
			get { return "Новости"; }
		}

		//Register method - creates custom news module role
		public override void Register(ModuleRegistrationData info)
		{
			// Check if role is already exists
			Role role = info.Data.Query<Role>().FirstOrDefault(r => r.Name == NewsRole);
			// add role
			if (role == null)
			{
				role = new Role()
				{
					Name = NewsRole,
					FriendlyName = "Менеджер новостей",
					Description = "Позволяет управлять списком новостей"
				};
				using (ITransaction t = info.Data.BeginTransaction())
				{
					info.Data.Save(role);
					t.Commit();
				}
			}

			base.Register(info);
		}

		/// <summary>
		/// Performs search in module.
		/// </summary>
		/// <param name="data">Current data session.</param>
		/// <param name="url">Url helper.</param>
		/// <param name="text">Text to search.</param>
		/// <returns>Search results.</returns>
		public override IEnumerable<SearchResult> Search(ISession data, UrlHelper url, string text)
		{
			return data.Query<NewsItem>()
				.Where(r => r.Title.Contains(text) || r.ShortText.Contains(text) || r.FullText.Contains(text))
				.OrderByDescending(r => r.Date)
				.ToList()
				.Select(r => new SearchResult(this, r.Title)
				{
					Url = url.ActionModule("Item", "News", Name, new { id = r.Id })
				})
				.ToList();
		}
	}
}